package com.cjw.config;

import com.cjw.enums.share.DeleteRemark;
import com.cjw.mapper.soulread.ReadMapper;
import com.cjw.pojo.entity.soulread.Read;
import com.cjw.service.soulread.HeatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author : cjw
 * @date: : 2022/3/30 19:11
 * @description : 排行榜定时任务
 */
@Component
@Slf4j
public class ReadRecommandScheduler {
    @Autowired
    private HeatService heatService;

    @Autowired
    private ReadMapper readMapper;

    private String heat = "heat";

    @Autowired
    private RedisTemplate redisTemplate;

    @Scheduled(cron = "0 0/30 * * * ?") // 每30分钟执行一次
    @Transactional(rollbackFor = Exception.class)
    public void lastHeat() {
        Read read = new Read();
        read.setDeleteRemark(DeleteRemark.UNDELETE.getCode());
        read.setIsPublic(1);// 公开，而且没有删除
        // 计算热度
        for (Read read1 : readMapper.select(read)) {
            Read read2 = new Read();
            read2.setId(read1.getId());
            read2.setScore(heatService.getHeat(read1.getId()));
            readMapper.updateByPrimaryKeySelective(read2);
        }
        redisTemplate.delete(heat);
        // 存储read的id到redis中
        for (Read read1 : readMapper.findAllHeat()) {
            redisTemplate.opsForZSet().add(heat, read1.getId(), read1.getScore());
        }
    }
}
